<template>
  <div class="page">
    <div class="custom-calendar">
      <!-- 日历头部 -->
      <div class="calendar-header">
        <!-- 当前日期显示 -->
        <span class="header-date">{{ displayDate }}</span>
        <!-- 回到今天按钮 -->
        <span class="header-today" v-if="goTodayHe" @click.stop="goToday">回到今天</span>
      </div>
      	<view class="top-bar">
          <u-icon class="top-bar-icon" @click="turningYear('prev')" name="arrow-left-double" size="20"></u-icon>
          <u-icon class="top-bar-icon" @click="turning('prev')" name="arrow-left" size="20"></u-icon>
          <view class="top-bar-ym">{{ textDate }}</view>
          <u-icon class="top-bar-icon" @click="turning('next')" name="arrow-right" size="20"></u-icon>
          <u-icon class="top-bar-icon" @click="turningYear('next')" name="arrow-right-double" size="20"></u-icon>
        </view>
      <!-- 日历内容区域，包括触摸事件监听 -->
      <div class="calendar-content" @touchstart="handleTouchStart" @touchmove="handleTouchMove"
        @touchend="handleTouchEnd">
        <!-- 星期标题 -->
        <div class="week-row">
          <div class="week-cell" v-for="day in fullWeekDays" :key="day">{{ day }}</div>
        </div>

        <!-- 日期网格 -->
        <div class="date-grid" :class="{ collapsed: !isExpanded }">
          <div class="date-cell" v-for="(date, index) in displayedDates" :key="index" :class="{
            'other-month': !date.isCurrentMonth, // 是否是当前月
            'today': date.isToday,              // 是否是今天
            'selected': date.isSelected         // 是否被选中
          }" @click="selectDate(date)">
            <div class="date-inner">{{ date.day }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>


<script>
export default {
  data () {
    return {
      currentDate: new Date(),
      isExpanded: true,
      fullWeekDays: ['一', '二', '三', '四', '五', '六', '日'],
      touchStartX: 0,
      touchEndX: 0
    }
  },
  created () {
    // 初始化时，根据当前日期计算当前月需要展示的日期
    // this.currentDate = new Date()

    this.$emit('date-change', this.currentDate)
  },
  computed: {
    // 展示的日期字符串，如 "2025 05.13"
    displayDate () {
      const year = this.currentDate.getFullYear()
      const month = (this.currentDate.getMonth() + 1).toString().padStart(2, '0')
      const day = this.currentDate.getDate().toString().padStart(2, '0')
      return `${year} | ${month}.${day}`
    },
    // 展示的日期字符串，如 "2025 05"
    textDate () {
      const year = this.currentDate.getFullYear()
      const month = (this.currentDate.getMonth() + 1).toString().padStart(2, '0')
      const day = this.currentDate.getDate().toString().padStart(2, '0')
      return `${year} 年 ${month} 月`
    },
    // 获取当前月需要展示的所有日期（含补充的前后月份）
    visibleDates () {
      const year = this.currentDate.getFullYear()
      const month = this.currentDate.getMonth()
      const today = new Date()

      const firstDay = new Date(year, month, 1)
      const lastDay = new Date(year, month + 1, 0)
      const firstDayOfWeek = firstDay.getDay() || 7 // 处理周日为 0 的情况

      const dates = []

      // 添加上个月的部分日期填充空格
      const prevMonthDays = firstDayOfWeek - 1
      const prevMonthLastDay = new Date(year, month, 0).getDate()
      for (let i = prevMonthDays; i > 0; i--) {
        const day = prevMonthLastDay - i + 1
        dates.push({
          day,
          date: new Date(year, month - 1, day),
          isCurrentMonth: false,
          isToday: false,
          isSelected: false
        })
      }

      // 当前月日期
      for (let i = 1; i <= lastDay.getDate(); i++) {
        const date = new Date(year, month, i)
        const isToday = date.toDateString() === today.toDateString()
        const isSelected = date.toDateString() === this.currentDate.toDateString()
        dates.push({
          day: i,
          date,
          isCurrentMonth: true,
          isToday,
          isSelected
        })
      }

      // 添加下个月的日期填补 6 行 × 7 列 = 42 个格子
      const remainingCells = 42 - dates.length
      for (let i = 1; i <= remainingCells; i++) {
        dates.push({
          day: i,
          date: new Date(year, month + 1, i),
          isCurrentMonth: false,
          isToday: false,
          isSelected: false
        })
      }

      return dates
    },

    // 根据是否展开来决定展示全部日期还是一周
    displayedDates () {
      if (this.isExpanded) {
        return this.visibleDates
      } else {
        // 找到当前选中日期所在周，并截取那一行
        const selectedIndex = this.visibleDates.findIndex(d => d.date.toDateString() === this.currentDate.toDateString())
        if (selectedIndex === -1) return []
        const startOfWeek = Math.floor(selectedIndex / 7) * 7
        return this.visibleDates.slice(startOfWeek, startOfWeek + 7)
      }
    },
    // 判断回到今天是否显示
    goTodayHe () {
      const today = new Date()
      const current = this.currentDate

      return (
        today.getFullYear() !== current.getFullYear() ||
        today.getMonth() !== current.getMonth() ||
        today.getDate() !== current.getDate()
      )
    }
  },
  watch: {

  },
  methods: {
    // 切换展开/收起状态
    toggleExpand () {

      this.isExpanded = !this.isExpanded
    },
    // 回到今天
    goToday () {
      this.currentDate = new Date()
      // this.$emit('date-change', this.currentDate)
    },
    // 选择某个日期
    selectDate (date) {

      this.currentDate = new Date(date.date)


      this.$emit('date-change', this.currentDate)
    },
    // 上个月
    prevMonth () {
      this.currentDate = new Date(this.currentDate.getFullYear(), this.currentDate.getMonth() - 1, 1)
      // this.$emit('month-change', this.currentDate)
    },
    // 下个月
    nextMonth () {
      this.currentDate = new Date(this.currentDate.getFullYear(), this.currentDate.getMonth() + 1, 1)
      // this.$emit('month-change', this.currentDate)
    },
    // 上一年
    prevYear () {
      this.currentDate = new Date(this.currentDate.getFullYear(), this.currentDate.getMonth() - 12, 1)
      // this.$emit('month-change', this.currentDate)
    },
    // 下一年
    nextYear () {
      this.currentDate = new Date(this.currentDate.getFullYear(), this.currentDate.getMonth() + 12, 1)
      // this.$emit('month-change', this.currentDate)
    },
    // 触摸开始事件
    handleTouchStart (e) {
      this.touchStartX = e.changedTouches[0].clientX
    },
    // 阻止默认行为（如滚动）
    handleTouchMove (e) {
      e.preventDefault()
    },
    // 触摸结束，触发滑动判断
    handleTouchEnd (e) {
      this.touchEndX = e.changedTouches[0].clientX
      this.handleSwipe()
    },
    // 判断滑动方向并翻月
    handleSwipe () {
      if (!this.isExpanded) return // 非展开状态不处理滑动
      const diffX = this.touchStartX - this.touchEndX
      const swipeThreshold = 50 // 最小滑动距离阈值

      if (diffX > swipeThreshold) {
        this.nextMonth()
      } else if (diffX < -swipeThreshold) {
        this.prevMonth()
      }
    },
		// 上个月，下个月
		turning(_action) {
      // 下个月
			if (_action === 'next') {
        this.nextMonth()
			} else {
				this.prevMonth()
			}
		},
		// 上一年，下一年
		turningYear(_action) {
        // 下一年
				if (_action === 'next') {
					this.nextYear()
				} else {
          this.prevYear()
				}
		}
  }
}
</script>

<style lang="scss" scoped>
.page {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
  user-select: none;

  .custom-calendar {
    width: 100%;
    background: #fff;
    border-radius: 4px;
    overflow: hidden;

    .calendar-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 16px;
      position: relative;

      .header-date {
        font-size: 16px;
        font-weight: bold;
        flex-grow: 1;
        text-align: left;
      }

      .header-today {
        position: absolute;
        left: 80%;
        transform: translateX(-50%);
        font-size: 14px;
        color: #ccc;
        cursor: pointer;
        text-align: right;
      }
    }

    .calendar-content {
      padding: 8px 0;
      touch-action: pan-y;

      .week-row {
        display: flex;
        padding: 8px 0;

        .week-cell {
          flex: 1;
          text-align: center;
          font-size: 12px;
          color: #666;
        }
      }

      .date-grid {
        display: flex;
        flex-wrap: wrap;

        &.collapsed {
          flex-wrap: nowrap;
        }

        .date-cell {
          flex: 0 0 14.28%;
          height: 36px;
          display: flex;
          justify-content: center;
          align-items: center;
          font-size: 14px;
          cursor: pointer;
          position: relative;

          .date-inner {
            width: 28px;
            height: 28px;
            line-height: 28px;
            text-align: center;
          }

          &.other-month {
            color: #ccc;
          }

          &.today .date-inner {
            color: #007aff;
            font-weight: bold;
          }

          &.selected .date-inner {
            background-color: #1890ff;
            color: white;
            border-radius: 50%;
          }
        }
      }
    }

    .calendar-toggle-line {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 8px 0;
      cursor: pointer;

      .line {
        flex: 1;
        height: 1px;
        background-color: #ccc;
        margin: 0 8px;
      }

      .arrow-icon {
        font-size: 14px;
        color: #666;
        padding: 0 4px;
      }
    }
  }

  .top-bar {
			display: flex;
			justify-content: space-between;
			padding: 0 24upx;
			height: 80upx;
			&.icon {
				width: 30upx;
			}
			.top-bar-ym{
        text-align: center;
				font-size: 32upx;
				height: 80upx;
				width: 340upx;	
				line-height: 80upx;
			}
			.top-change-month{	
				height: 80upx;
				width: 80upx;
			}
	}

}
</style>